<template>
  <div class="container">
    <el-divider content-position="left"><span class="title-left-color">基本信息</span></el-divider>
    <el-form ref="formRef" :model="form" :rules="rules" v-loading="loading" label-width="150px">
      <el-row :gutter="10">
        <el-col :span="10">
          <el-form-item label="分类名称：" prop="name">
            <el-input v-model.trim="form.name" placeholder="分类名称"> </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="排序：" prop="sort">
            <el-input v-model.number="form.sort" placeholder="请填写排序"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="10">
          <el-form-item label="是否显示：" prop="status">
            <el-switch v-model="form.status" :active-value="1" :inactive-value="0" active-text="是" inactive-text="否"></el-switch>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="10">
          <el-form-item label="图片：" prop="image">
            <UploadImageInfo :limit="500" suggestInfo="建议：尺寸80*66像素,大小500k以下。" v-model:disabledbtn="disabledbtn" v-model:loading="loading" imageKey="image" v-model:form="form" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="footer-center">
      <el-button :disabled="disabledbtn" @click="cancelSubmit">取 消</el-button>
      <el-button type="primary" :disabled="disabledbtn" v-if="!isDisabledbtn" @click="submitForm">确 定</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import UploadImageInfo from "@/components/common/UploadImageInfo.vue";
import type { postOrPutType } from "@/constants";
import type { ViewMode } from "@/types/common";
import { useState } from "@/hooks/useState.ts";
import type { IRecycleCategory } from "@/types/recoveryManage/recycleCategory";
import { commonRecycleCategoryInfo } from "@/utils/api/recycleCategory";
const { disabledbtn, loading, toggleState } = useState();

const formStatus = defineModel<ViewMode>("formStatus", { required: true });
const form = defineModel<IRecycleCategory>("form", { required: true });
const emit = defineEmits<{
  handleInitData: [];
  handleSuccess: [];
}>();

const isDisabledbtn = ref(false);
const formRef = useTemplateRef("formRef");
const methodType = ref<postOrPutType>("PUT");

const rules = reactive({
  name: [{ required: true, message: "请输入分类名称", trigger: "blur" }],
  sort: [{ required: true, message: "请输入排序顺序", trigger: "blur" }]
});

onMounted(() => {
  console.log("Component mounted!");
});

/* formStatus处理器 */
const statusHandlers: Record<ViewMode, () => void> = {
  view: () => {
    isDisabledbtn.value = true;
  },
  edit: () => {
    methodType.value = "PUT";
  },
  add: () => {
    methodType.value = "POST";
  },
  none: () => {
    /* 初始化数据 */
    handleInitData();
  }
};
/* 监听formStatus,新增，编辑，查看的时候都可以打开模态框，又是有不同的操作和效果，需要单独判断，none为模态框关闭的情况，需要初始化数据 */
watch(formStatus, newValue => {
  const handler = statusHandlers[newValue];
  handler?.();
});

/* 初始化数据 */
function handleInitData() {
  methodType.value = "POST";
  isDisabledbtn.value = false;

  formRef.value?.resetFields();
  formRef.value?.clearValidate();
}

/* 保存或编辑 */
function submitForm() {
  if (!formRef.value) return;
  formRef.value.validate(valid => {
    if (!valid) {
      ElMessage.warning("请填写必填字段");
      return;
    }
    submitFormInfo();
  });
}

/* 保存或编辑信息 */
function submitFormInfo() {
  /* 防止多次提交 */
  toggleState(true);
  commonRecycleCategoryInfo(form.value, methodType.value)
    .then(res => {
      ElMessage.success(res.msg);
      cancelSubmit();
      emit("handleSuccess");
    })
    .catch(() => {})
    .finally(() => {
      toggleState(false);
    });
}
/* 保存或编辑 取消提交 */
function cancelSubmit() {
  // clearData();
  // activeName = "one";
  emit("handleInitData");
}
</script>

<style lang="scss" scoped>
/* 修改select的盒模型 */
.el-select {
  display: block;
}
/* 底部按钮居中 */
.footer-center {
  margin: 10px 0;
  text-align: center;
}
</style>
